<?php

require_once("$CFG->libdir/externallib.php");
require_once("$CFG->libdir/gradelib.php");
require_once("$CFG->libdir/filelib.php");
require_once("$CFG->dirroot/user/lib.php");
require_once("$CFG->dirroot/calendar/lib.php");

class local_moodlin8_external extends external_api {

    public static function get_assignments_parameters() {
        return new external_function_parameters(
            array(
                'courseids' => new external_multiple_structure(
                    new external_value(PARAM_INT, 'course id'),
                    '0 or more course ids',
                    VALUE_DEFAULT, array()
                ),
                'capabilities'  => new external_multiple_structure(
                    new external_value(PARAM_CAPABILITY, 'capability'),
                    'list of capabilities used to filter courses',
                    VALUE_DEFAULT, array()
                )
            )
        );
    }

    public static function get_assignments($courseids = array(), $capabilities = array()) {
        global $USER, $DB, $CFG;

        $params = self::validate_parameters(
            self::get_assignments_parameters(),
            array('courseids' => $courseids, 'capabilities' => $capabilities)
        );

        $warnings = array();
        $fields = 'sortorder,shortname,fullname,timemodified';
        $courses = enrol_get_users_courses($USER->id, true, $fields);
        // Used to test for ids that have been requested but can't be returned.
        if (count($params['courseids']) > 0) {
            foreach ($params['courseids'] as $courseid) {
                if (!in_array($courseid, array_keys($courses))) {
                    unset($courses[$courseid]);
                    $warnings[] = array(
                        'item' => 'course',
                        'itemid' => $courseid,
                        'warningcode' => '2',
                        'message' => 'User is not enrolled or does not have requested capability'
                    );
                }
            }
        }
        foreach ($courses as $id => $course) {
            if (count($params['courseids']) > 0 && !in_array($id, $params['courseids'])) {
                unset($courses[$id]);
            }
            $context = context_course::instance($id);
            try {
                self::validate_context($context);
            } catch (Exception $e) {
                unset($courses[$id]);
                $warnings[] = array(
                    'item' => 'course',
                    'itemid' => $id,
                    'warningcode' => '1',
                    'message' => 'No access rights in course context '.$e->getMessage().$e->getTraceAsString()
                );
                continue;
            }
            if (count($params['capabilities']) > 0 && !has_all_capabilities($params['capabilities'], $context)) {
                unset($courses[$id]);
            }
        }
        $extrafields='m.id as assignmentid, m.course, m.nosubmissions, m.submissiondrafts, m.sendnotifications, '.
                     'm.sendlatenotifications, m.duedate, m.allowsubmissionsfromdate, m.grade, m.timemodified, '.
                     'm.completionsubmit, m.cutoffdate, m.teamsubmission, m.requireallteammemberssubmit, '.
                     'm.teamsubmissiongroupingid, m.blindmarking, m.revealidentities, m.requiresubmissionstatement, m.intro, m.introformat';
        $coursearray = array();
        foreach ($courses as $id => $course) {
            $assignmentarray = array();
            // Get a list of assignments for the course.
            if ($modules = get_coursemodules_in_course('assign', $courses[$id]->id, $extrafields)) {
                foreach ($modules as $module) {
                    $context = context_module::instance($module->id);
                    try {
                        self::validate_context($context);
                        require_capability('mod/assign:view', $context);
                    } catch (Exception $e) {
                        $warnings[] = array(
                            'item' => 'module',
                            'itemid' => $module->id,
                            'warningcode' => '1',
                            'message' => 'No access rights in module context'
                        );
                        continue;
                    }
                    $configrecords = $DB->get_recordset('assign_plugin_config', array('assignment' => $module->assignmentid));
                    $configarray = array();
                    foreach ($configrecords as $configrecord) {
                        $configarray[] = array(
                            'id' => $configrecord->id,
                            'assignment' => $configrecord->assignment,
                            'plugin' => $configrecord->plugin,
                            'subtype' => $configrecord->subtype,
                            'name' => $configrecord->name,
                            'value' => $configrecord->value
                        );
                    }
                    $configrecords->close();

                    $gradesrecord = grade_get_grades($module->course, 'mod', 'assign', $module->assignmentid, $USER->id);
		    $gradesarray = array(
		        'items' => array(),
		    );
		    foreach ($gradesrecord->items as $item) {
		        $gradeitemarray = array(
			    'scaleid' => $item->scaleid,
			    'grademin' => $item->grademin,
			    'grademax' => $item->grademax,
			    'gradepass' => $item->gradepass,
			    'locked' => $item->locked,
			    'hidden' => $item->hidden,
			    'grades' => array()
			);
			foreach ($item->grades as $key => $grade) {
			    $gradeitemarray['grades'][] = array(
			        'grade' => $grade->grade,
				'locked' => $grade->locked,
				'hidden' => $grade->hidden,
				'overridden' => $grade->overridden,
				'feedback' => $grade->feedback,
				'feedbackformat' => $grade->feedbackformat,
				'usermodified' => $grade->usermodified,
				'datesubmitted' => $grade->datesubmitted,
				'dategraded' => $grade->dategraded,
				'str_grade' => $grade->str_grade,
				'str_long_grade' => $grade->str_long_grade,
				'str_feedback' => $grade->str_feedback
			    );
			}
			$gradesarray['items'][] = $gradeitemarray;
		    }

                    $assignmentarray[]= array(
                        'id' => $module->assignmentid,
                        'cmid' => $module->id,
                        'course' => $module->course,
                        'name' => $module->name,
                        'nosubmissions' => $module->nosubmissions,
                        'submissiondrafts' => $module->submissiondrafts,
                        'sendnotifications' => $module->sendnotifications,
                        'sendlatenotifications' => $module->sendlatenotifications,
                        'duedate' => $module->duedate,
                        'allowsubmissionsfromdate' => $module->allowsubmissionsfromdate,
                        'grade' => $module->grade,
                        'timemodified' => $module->timemodified,
                        'completionsubmit' => $module->completionsubmit,
                        'cutoffdate' => $module->cutoffdate,
                        'teamsubmission' => $module->teamsubmission,
                        'requireallteammemberssubmit' => $module->requireallteammemberssubmit,
                        'teamsubmissiongroupingid' => $module->teamsubmissiongroupingid,
                        'blindmarking' => $module->blindmarking,
                        'revealidentities' => $module->revealidentities,
                        'requiresubmissionstatement' => $module->requiresubmissionstatement,
                        'intro' => $module->intro,
                        'introformat' => $module->introformat,
                        'configs' => $configarray,
			'grades' => $gradesarray
                    );
                }
            }
            $coursearray[]= array(
                'id' => $courses[$id]->id,
                'fullname' => $courses[$id]->fullname,
                'shortname' => $courses[$id]->shortname,
                'timemodified' => $courses[$id]->timemodified,
                'assignments' => $assignmentarray
            );
        }

        $result = array(
            'courses' => $coursearray,
            'warnings' => $warnings
        );
        return $result;
    }

    private static function get_assignments_assignment_structure() {
        return new external_single_structure(
            array(
                'id' => new external_value(PARAM_INT, 'assignment id'),
                'course' => new external_value(PARAM_INT, 'course id'),
                'name' => new external_value(PARAM_TEXT, 'assignment name'),
                'nosubmissions' => new external_value(PARAM_INT, 'no submissions'),
                'submissiondrafts' => new external_value(PARAM_INT, 'submissions drafts'),
                'sendnotifications' => new external_value(PARAM_INT, 'send notifications'),
                'sendlatenotifications' => new external_value(PARAM_INT, 'send notifications'),
                'duedate' => new external_value(PARAM_INT, 'assignment due date'),
                'allowsubmissionsfromdate' => new external_value(PARAM_INT, 'allow submissions from date'),
                'grade' => new external_value(PARAM_INT, 'grade type'),
                'timemodified' => new external_value(PARAM_INT, 'last time assignment was modified'),
                'completionsubmit' => new external_value(PARAM_INT, 'if enabled, set activity as complete following submission'),
                'cutoffdate' => new external_value(PARAM_INT, 'date after which submission is not accepted without an extension'),
                'teamsubmission' => new external_value(PARAM_INT, 'if enabled, students submit as a team'),
                'requireallteammemberssubmit' => new external_value(PARAM_INT, 'if enabled, all team members must submit'),
                'teamsubmissiongroupingid' => new external_value(PARAM_INT, 'the grouping id for the team submission groups'),
                'blindmarking' => new external_value(PARAM_INT, 'if enabled, hide identities until reveal identities actioned'),
                'revealidentities' => new external_value(PARAM_INT, 'show identities for a blind marking assignment'),
                'requiresubmissionstatement' => new external_value(PARAM_INT, 'student must accept submission statement'),
                'intro' => new external_value(PARAM_RAW, 'assignment intro'),
                'introformat' => new external_value(PARAM_INT, 'intro format'),
                'configs' => new external_multiple_structure(self::get_assignments_config_structure(), 'configuration settings'),
		'grades' => self::get_assignments_grade_external_structure()
            ), 'assignment information object');
    }

    private static function get_assignments_config_structure() {
        return new external_single_structure(
            array(
                'id' => new external_value(PARAM_INT, 'assign_plugin_config id'),
                'assignment' => new external_value(PARAM_INT, 'assignment id'),
                'plugin' => new external_value(PARAM_TEXT, 'plugin'),
                'subtype' => new external_value(PARAM_TEXT, 'subtype'),
                'name' => new external_value(PARAM_TEXT, 'name'),
                'value' => new external_value(PARAM_TEXT, 'value')
            ), 'assignment configuration object'
        );
    }

    private static function get_assignments_course_structure() {
        return new external_single_structure(
            array(
                'id' => new external_value(PARAM_INT, 'course id'),
                'fullname' => new external_value(PARAM_TEXT, 'course full name'),
                'shortname' => new external_value(PARAM_TEXT, 'course short name'),
                'timemodified' => new external_value(PARAM_INT, 'last time modified'),
                'assignments' => new external_multiple_structure(self::get_assignments_assignment_structure(), 'assignment info')
              ), 'course information object'
        );
    }

    private static function get_assignments_grade_structure() {
	return new external_single_structure(
	    array(
	        'grade' => new external_value(PARAM_FLOAT, 'grade'),
		'locked' => new external_value(PARAM_BOOL, 'locked'),
		'hidden' => new external_value(PARAM_BOOL, 'hidden'),
		'overridden' => new external_value(PARAM_BOOL, 'overridden'),
		'feedback' => new external_value(PARAM_RAW, 'feedback'),
		'feedbackformat' => new external_value(PARAM_INT, 'feedback format'),
		'usermodified' => new external_value(PARAM_INT, 'user modified'),
		'datesubmitted' => new external_value(PARAM_INT, 'date submitted'),
		'dategraded' => new external_value(PARAM_INT, 'date graded'),
		'str_grade' => new external_value(PARAM_TEXT, 'grade'),
		'str_long_grade' => new external_value(PARAM_TEXT, 'long grade'),
		'str_feedback' => new external_value(PARAM_RAW, 'feedback')
	    ), 'grade object'
	);
    }

     private static function get_assignments_grade_item_structure() {
	return new external_single_structure(
	    array(
	        'scaleid' => new external_value(PARAM_INT, 'scale id'),
		'grademin' => new external_value(PARAM_FLOAT, 'grade min'),
		'grademax' => new external_value(PARAM_FLOAT, 'grade max'),
		'gradepass' => new external_value(PARAM_FLOAT, 'grade pass'),
		'locked' => new external_value(PARAM_BOOL, 'locked'),
		'hidden' => new external_value(PARAM_BOOL, 'hidden'),
		'grades' => new external_multiple_structure(self::get_assignments_grade_structure(), 'grades')
	    ), 'grade item object'
	);
    }

    private static function get_assignments_grade_external_structure() {
	return new external_single_structure(
	    array(
	        'items' => new external_multiple_structure(self::get_assignments_grade_item_structure(), 'grade items')
	    ), 'grade external object'
	);
    }

    public static function get_assignments_returns() {
        return new external_single_structure(
            array(
                'courses' => new external_multiple_structure(self::get_assignments_course_structure(), 'list of courses'),
                //'warnings'  => new external_warnings()
            )
        );
    }

    public static function get_files_parameters() {
        return new external_function_parameters(
            array(
                'filepath' => new external_value(PARAM_TEXT, 'The filepath', VALUE_DEFAULT, '/'),
            )
        );
    }

    public static function get_files($filepath = '/') {
        global $CFG, $USER, $OUTPUT;
        $req_params = self::validate_parameters(self::get_files_parameters(), array(
            'filepath' => $filepath,
        ));
        $browser = get_file_browser();

        $context = context_user::instance($USER->id);
        $fileinfo = array(
            'component' => 'user',
            'filearea' => 'private',
            'itemid' => 0,
            'filepath' => $req_params['filepath'],
            'filename' => '',
        );

        $return = array();
        $return['parents'] = array();
        $return['files'] = array();
        $list = array();
        if ($file = $browser->get_file_info(
            $context, $fileinfo['component'], $fileinfo['filearea'], $fileinfo['itemid'],
                $fileinfo['filepath'], $fileinfo['filename'])) {
            $level = $file->get_parent();
            while ($level) {
                $params = $level->get_params();
                $params['filename'] = $level->get_visible_name();
                array_unshift($return['parents'], $params);
                $level = $level->get_parent();
            }
            $children = $file->get_children();
            foreach ($children as $child) {

                $params = $child->get_params();
                $timemodified = $child->get_timemodified();

                if ($child->is_directory()) {
                    if ((is_null($modified)) or ($modified < $timemodified)) {
                        $node = array(
                            'contextid' => $params['contextid'],
                            'component' => $params['component'],
                            'filearea'  => $params['filearea'],
                            'itemid'    => $params['itemid'],
                            'filepath'  => $params['filepath'],
                            'filename'  => $child->get_visible_name(),
                            'url'       => null,
                            'isdir'     => true,
                            'timemodified' => $timemodified
                           );
                           $list[] = $node;
                    }
                } else {
                    if ((is_null($modified)) or ($modified < $timemodified)) {
                        $node = array(
                            'contextid' => $params['contextid'],
                            'component' => $params['component'],
                            'filearea'  => $params['filearea'],
                            'itemid'    => $params['itemid'],
                            'filepath'  => $params['filepath'],
                            'filename'  => $child->get_visible_name(),
                            'url'       => $child->get_url(),
                            'isdir'     => false,
                            'timemodified' => $timemodified
                        );
                           $list[] = $node;
                    }
                }
            }
        }
        $return['files'] = $list;
        return $return;
    } 

    public static function get_files_returns() {
        return new external_single_structure(
            array(
                'parents' => new external_multiple_structure(
                    new external_single_structure(
                        array(
                            'contextid' => new external_value(PARAM_INT, ''),
                            'component' => new external_value(PARAM_COMPONENT, ''),
                            'filearea'  => new external_value(PARAM_AREA, ''),
                            'itemid'    => new external_value(PARAM_INT, ''),
                            'filepath'  => new external_value(PARAM_TEXT, ''),
                            'filename'  => new external_value(PARAM_TEXT, ''),
                        )
                    )
                ),
                'files' => new external_multiple_structure(
                    new external_single_structure(
                        array(
                            'contextid' => new external_value(PARAM_INT, ''),
                            'component' => new external_value(PARAM_COMPONENT, ''),
                            'filearea'  => new external_value(PARAM_AREA, ''),
                            'itemid'   => new external_value(PARAM_INT, ''),
                            'filepath' => new external_value(PARAM_TEXT, ''),
                            'filename' => new external_value(PARAM_FILE, ''),
                            'isdir'    => new external_value(PARAM_BOOL, ''),
                            'url'      => new external_value(PARAM_TEXT, ''),
                            'timemodified' => new external_value(PARAM_INT, ''),
                        )
                    )
                )
            )
        );
    }

    public static function download_file_parameters() {
        return new external_function_parameters(
            array(
                'filename' => new external_value(PARAM_TEXT, 'The filename'),
                'filepath' => new external_value(PARAM_TEXT, 'The filepath', VALUE_DEFAULT, '/'),
            )
        );
    }

    public static function download_file($filename, $filepath = '/') {
        global $CFG, $USER, $OUTPUT;
        $params = self::validate_parameters(self::download_file_parameters(), array(
            'filename' => $filename,
            'filepath' => $filepath,
        ));
        $browser = get_file_browser();

        $context = context_user::instance($USER->id);
        $fileinfo = array(
            'component' => 'user',
            'filearea' => 'private',
            'itemid' => 0,
            'filepath' => $params['filepath'],
            'filename' => $params['filename'],
        );

        $result = array('file' => null,);
        if ($file = $browser->get_file_info(
            $context, $fileinfo['component'], $fileinfo['filearea'], $fileinfo['itemid'],
                $fileinfo['filepath'], $fileinfo['filename'])) {
            if (!$file->is_directory() && $file->is_readable()) {
                $tmp = tmpfile();
                $meta_data = stream_get_meta_data($tmp);
                $filename = $meta_data['uri'];
                if ($file->copy_to_pathname($filename)) {
                    $result['file'] = base64_encode(file_get_contents($filename));
                }
                fclose($tmp);
            }
        }

        return $result;
    }

    public static function download_file_returns() {
        return new external_single_structure(
            array(
                'file' => new external_value(PARAM_RAW, ''),
            ));
    }

    public static function get_conversation_parameters() {
        return new external_function_parameters(
            array(
                'userid' => new external_value(PARAM_INT, 'The user id'),
            )
        );
    }

    public static function get_conversation($userid) {
        global $CFG, $USER, $DB;
        $params = self::validate_parameters(self::get_conversation_parameters(), array(
            'userid' => $userid,
        ));
        $userid = $params['userid'];
        $return = array();

        $messages = array();
        $notificationwhere = 'AND NOT (useridfrom=? AND notification=1)';
        $read = $DB->get_records_select('message_read', "((useridfrom = ? AND useridto = ?) OR (useridto = ? AND useridfrom = ?)) $notificationwhere", array($USER->id, $userid, $USER->id, $userid, $USER->id));
        $new = $DB->get_records_select('message', "((useridfrom = ? AND useridto = ?) OR (useridto = ? AND useridfrom = ?)) $notificationwhere", array($USER->id, $userid, $USER->id, $userid, $USER->id));
        if ($read)
            foreach ($read as $m)
                $messages[] = $m;
        if ($new)
            foreach ($new as $m)
                $messages[] = $m;

        foreach ($messages as $m) {
            $return[] = array(
                'id' => $m->id,
                'useridfrom' => $m->useridfrom,
                'useridto' => $m->useridto,
                'subject' => $m->subject,
                'fullmessage' => $m->fullmessage,
                'fullmessageformat' => $m->fullmessageformat,
                'fullmessagehtml' => $m->fullmessagehtml,
                'smallmessage' => $m->smallmessage,
                'notification' => $m->notification,
                'timecreated' => $m->timecreated,
                'timeread' => $m->timeread,
            );
        }

        return $return;
    }

    public static function get_conversation_returns() {
        return new external_multiple_structure(
                new external_single_structure(
                    array(
                        'id' => new external_value(PARAM_INT, ''),
                        'useridfrom' => new external_value(PARAM_INT, ''),
                        'useridto' => new external_value(PARAM_INT, ''),
                        'subject' => new external_value(PARAM_TEXT, ''),
                        'fullmessage'  => new external_value(PARAM_TEXT, ''),
                        'fullmessageformat'    => new external_value(PARAM_INT, ''),
                        'fullmessagehtml'  => new external_value(PARAM_RAW, ''),
                        'smallmessage'  => new external_value(PARAM_RAW, ''),
                        'notification'  => new external_value(PARAM_BOOL, ''),
                        'timecreated'  => new external_value(PARAM_INT, ''),
                        'timeread'  => new external_value(PARAM_INT, '', VALUE_OPTIONAL),
                    )
                )
        );
    }

    public static function get_messages_parameters() {
        return new external_function_parameters(
            array(
            )
        );
    }

    public static function get_messages() {
        global $CFG, $USER, $DB;
        $params = self::validate_parameters(self::get_messages_parameters(), array(
        ));

        $return = array();

        $messages = array();
        $notificationwhere = 'AND NOT (useridfrom=? AND notification=1)';
        $read = $DB->get_records_select('message_read', "(useridto = ?) $notificationwhere", array($USER->id, $USER->id));
        $new = $DB->get_records_select('message', "(useridto = ?) $notificationwhere", array($USER->id, $USER->id));
        $userids = array();
        if ($read)
            foreach ($read as $m) {
                $messages[] = $m;
                $userids[] = $m->useridfrom;
                $userids[] = $m->useridto;
            }
        if ($new)
            foreach ($new as $m) {
                $messages[] = $m;
                $userids[] = $m->useridfrom;
                $userids[] = $m->useridto;
            }
        $userids = array_unique($userids);
        $users = $DB->get_records_list('user', 'id', $userids);
        foreach ($users as $user) {
            $uc = context_user::instance($user->id);
            $user->fullname = fullname($user);
            $user->profileimageurl = moodle_url::make_pluginfile_url($uc->id, 'user', 'icon', NULL, '/', 'f1')->out(false);
            $user->profileimageurlsmall = moodle_url::make_pluginfile_url($uc->id, 'user', 'icon', NULL, '/', 'f2')->out(false);
        }
        collatorlib::asort_objects_by_property($messages, 'timecreated', collatorlib::SORT_NUMERIC);

        foreach ($messages as $m) {
            $return[] = array(
                'id' => $m->id,
                'useridfrom' => $m->useridfrom,
                'userfrom' => self::prepare_user_for_message($users[$m->useridfrom]),
                'useridto' => $m->useridto,
                'userto' => self::prepare_user_for_message($users[$m->useridto]),
                'subject' => $m->subject,
                'fullmessage' => $m->fullmessage,
                'fullmessageformat' => $m->fullmessageformat,
                'fullmessagehtml' => $m->fullmessagehtml,
                'smallmessage' => $m->smallmessage,
                'notification' => $m->notification,
                'timecreated' => $m->timecreated,
                'timeread' => $m->timeread,
            );
        }

        return $return;
    }

    private static function prepare_user_for_message($user) {
        return array(
            'id' => $user->id,
            'fullname' => $user->fullname,
            'profileimageurl' => $user->profileimageurl,
            'profileimageurlsmall' => $user->profileimageurlsmall,
        );
    }

    public static function get_messages_returns() {
        return new external_multiple_structure(
                new external_single_structure(
                    array(
                        'id' => new external_value(PARAM_INT, ''),
                        'useridfrom' => new external_value(PARAM_INT, ''),
                        'userfrom' => self::get_messages_user_returns(),
                        'useridto' => new external_value(PARAM_INT, ''),
                        'userto' => self::get_messages_user_returns(),
                        'subject' => new external_value(PARAM_TEXT, ''),
                        'fullmessage'  => new external_value(PARAM_TEXT, ''),
                        'fullmessageformat'    => new external_value(PARAM_INT, ''),
                        'fullmessagehtml'  => new external_value(PARAM_RAW, ''),
                        'smallmessage'  => new external_value(PARAM_RAW, ''),
                        'notification'  => new external_value(PARAM_BOOL, ''),
                        'timecreated'  => new external_value(PARAM_INT, ''),
                        'timeread'  => new external_value(PARAM_INT, '', VALUE_OPTIONAL),
                    )
                )
        );
    }

    private static function get_messages_user_returns() {
        return new external_single_structure(
            array(
                'id' => new external_value(PARAM_INT, ''),
                'fullname' => new external_value(PARAM_TEXT, ''),
                'profileimageurl' => new external_value(PARAM_URL, ''),
                'profileimageurlsmall' => new external_value(PARAM_URL, ''),
            )
        );
    }

    public static function upload_file_parameters() {
        return new external_function_parameters(
            array(
                //'contextid' => new external_value(PARAM_INT, 'context id'),
                'component' => new external_value(PARAM_COMPONENT, 'component'),
                'filearea'  => new external_value(PARAM_AREA, 'file area'),
                'itemid'    => new external_value(PARAM_INT, 'associated id'),
                'filepath'  => new external_value(PARAM_PATH, 'file path'),
                'filename'  => new external_value(PARAM_FILE, 'file name'),
                'filecontent' => new external_value(PARAM_TEXT, 'file content')
            )
        );
    }

    public static function upload_file($component, $filearea, $itemid, $filepath, $filename, $filecontent) {
        global $CFG, $USER, $OUTPUT;
        $fileinfo = self::validate_parameters(self::upload_file_parameters(), array(
            'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid,
            'filepath'=>$filepath, 'filename'=>$filename, 'filecontent'=>$filecontent,
        ));

        if (!isset($fileinfo['filecontent'])) {
            throw new moodle_exception('nofile');
        }

        // Saving file.
        $dir = make_temp_directory('wsupload');

        if (empty($fileinfo['filename'])) {
            $filename = uniqid('wsupload', true).'_'.time().'.tmp';
        } else {
            $filename = $fileinfo['filename'];
        }

        if (file_exists($dir.$filename)) {
            $savedfilepath = $dir.uniqid('m').$filename;
        } else {
            $savedfilepath = $dir.$filename;
        }

        file_put_contents($savedfilepath, base64_decode($fileinfo['filecontent']));
        unset($fileinfo['filecontent']);

        if (!empty($fileinfo['filepath'])) {
            $filepath = $fileinfo['filepath'];
        } else {
            $filepath = '/';
        }

        if (isset($fileinfo['itemid'])) {
            // TODO MDL-31116 in user private area, itemid is always 0.
            $itemid = 0;
        } else {
            throw new coding_exception('itemid cannot be empty');
        }

        /*if (!empty($fileinfo['contextid'])) {
            $context = context::instance_by_id($fileinfo['contextid']);
        } else {
            $context = get_system_context();
        }*/
        $context = context_user::instance($USER->id);

        if (!($fileinfo['component'] == 'user' and $fileinfo['filearea'] == 'private')) {
            throw new coding_exception('File can be uploaded to user private area only');
        } else {
            // TODO MDL-31116 hard-coded to use user_private area.
            $component = 'user';
            $filearea = 'private';
        }

        $browser = get_file_browser();

        // Check existing file.
        if ($file = $browser->get_file_info($context, $component, $filearea, $itemid, $filepath, $filename)) {
            throw new moodle_exception('fileexist');
        }

        // Move file to filepool.
        if ($dir = $browser->get_file_info($context, $component, $filearea, $itemid, $filepath, '.')) {
            $info = $dir->create_file_from_pathname($filename, $savedfilepath);
            $params = $info->get_params();
            unlink($savedfilepath);
            return array(
                'contextid'=>$params['contextid'],
                'component'=>$params['component'],
                'filearea'=>$params['filearea'],
                'itemid'=>$params['itemid'],
                'filepath'=>$params['filepath'],
                'filename'=>$params['filename'],
                'url'=>$info->get_url()
                );
        } else {
            throw new moodle_exception('nofile');
        }
    }

    public static function upload_file_returns() {
        return new external_single_structure(
             array(
                 'contextid' => new external_value(PARAM_INT, ''),
                 'component' => new external_value(PARAM_COMPONENT, ''),
                 'filearea'  => new external_value(PARAM_AREA, ''),
                 'itemid'   => new external_value(PARAM_INT, ''),
                 'filepath' => new external_value(PARAM_TEXT, ''),
                 'filename' => new external_value(PARAM_FILE, ''),
                 'url'      => new external_value(PARAM_TEXT, ''),
             )
        );
    }

    /***** CONTACTS *****/

    public static function get_contacts_parameters() {
        return new external_function_parameters(
            array(
            )
        );
    }

    public static function get_contacts() {
        global $CFG, $USER, $DB;
        $courses = enrol_get_users_courses($USER->id, true, 'id');
        
        $users = array();
        foreach ($courses as $course) {
            $courseid = $course->id;
            $coursecontext = context_course::instance($courseid, IGNORE_MISSING);
            if ($courseid == SITEID)
                $context = get_system_context();
            else
                $context = $coursecontext;
            try {
                self::validate_context($context);
                if ($courseid == SITEID) {
                    require_capability('moodle/site:viewparticipants', $context);
                } else {
                    require_capability('moodle/course:viewparticipants', $context);
                }
            }
            catch (Exception $e) {
                continue; // Skip invalid courses
            }
            list($enrolledsql, $enrolledparams) = get_enrolled_sql($coursecontext, false, false, false);
            list($ctxselect, $ctxjoin) = context_instance_preload_sql('u.id', CONTEXT_USER, 'ctx');
            $sqlparams['courseid'] = $courseid;
            $sql = "SELECT u.* $ctxselect
                      FROM {user} u $ctxjoin
                     WHERE u.id IN ($enrolledsql)
                     ORDER BY u.id ASC";
            $enrolledusers = $DB->get_recordset_sql($sql, $enrolledparams, $limitfrom, $limitnumber);
            foreach ($enrolledusers as $user) {
                if (isset($users[$user->id])) continue;
                context_instance_preload($user);
                if ($userdetails = user_get_user_details($user, $course, array())) {
                    $users[$user->id] = $userdetails;
                }
            }
        }
        return $users;
    }

    public static function get_contacts_returns() {
        return new external_multiple_structure(
	    new external_single_structure(
	        array(
                    'id'    => new external_value(PARAM_NUMBER, 'ID of the user'),
                    'username'    => new external_value(PARAM_RAW, 'Username', VALUE_OPTIONAL),
                    'firstname'   => new external_value(PARAM_NOTAGS, 'The first name(s) of the user', VALUE_OPTIONAL),
                    'lastname'    => new external_value(PARAM_NOTAGS, 'The family name of the user', VALUE_OPTIONAL),
                    'fullname'    => new external_value(PARAM_NOTAGS, 'The fullname of the user'),
                    'email'       => new external_value(PARAM_TEXT, 'Email address', VALUE_OPTIONAL),
                    'address'     => new external_value(PARAM_MULTILANG, 'Postal address', VALUE_OPTIONAL),
                    'phone1'      => new external_value(PARAM_NOTAGS, 'Phone 1', VALUE_OPTIONAL),
                    'phone2'      => new external_value(PARAM_NOTAGS, 'Phone 2', VALUE_OPTIONAL),
                    'icq'         => new external_value(PARAM_NOTAGS, 'icq number', VALUE_OPTIONAL),
                    'skype'       => new external_value(PARAM_NOTAGS, 'skype id', VALUE_OPTIONAL),
                    'yahoo'       => new external_value(PARAM_NOTAGS, 'yahoo id', VALUE_OPTIONAL),
                    'aim'         => new external_value(PARAM_NOTAGS, 'aim id', VALUE_OPTIONAL),
                    'msn'         => new external_value(PARAM_NOTAGS, 'msn number', VALUE_OPTIONAL),
                    'department'  => new external_value(PARAM_TEXT, 'department', VALUE_OPTIONAL),
                    'institution' => new external_value(PARAM_TEXT, 'institution', VALUE_OPTIONAL),
                    'interests'   => new external_value(PARAM_TEXT, 'user interests (separated by commas)', VALUE_OPTIONAL),
                    'firstaccess' => new external_value(PARAM_INT, 'first access to the site (0 if never)', VALUE_OPTIONAL),
                    'lastaccess'  => new external_value(PARAM_INT, 'last access to the site (0 if never)', VALUE_OPTIONAL),
                    'description' => new external_value(PARAM_RAW, 'User profile description', VALUE_OPTIONAL),
                    'descriptionformat' => new external_value(PARAM_INT, 'User profile description format', VALUE_OPTIONAL),
                    'city'        => new external_value(PARAM_NOTAGS, 'Home city of the user', VALUE_OPTIONAL),
                    'url'         => new external_value(PARAM_URL, 'URL of the user', VALUE_OPTIONAL),
                    'country'     => new external_value(PARAM_ALPHA, 'Country code of the user, such as AU or CZ', VALUE_OPTIONAL),
                    'profileimageurlsmall' => new external_value(PARAM_URL, 'User image profile URL - small', VALUE_OPTIONAL),
                    'profileimageurl' => new external_value(PARAM_URL, 'User image profile URL - big', VALUE_OPTIONAL),
                    'customfields' => new external_multiple_structure(
                        new external_single_structure(
                            array(
                                'type'  => new external_value(PARAM_ALPHANUMEXT, 'The type of the custom field'),
                                'value' => new external_value(PARAM_RAW, 'The value of the custom field'),
                                'name' => new external_value(PARAM_RAW, 'The name of the custom field'),
                                'shortname' => new external_value(PARAM_RAW, 'The shortname of the custom field'),
                            )
                        ), 'User custom fields (also known as user profil fields)', VALUE_OPTIONAL),
                    'groups' => new external_multiple_structure(
                        new external_single_structure(
                            array(
                                'id'  => new external_value(PARAM_INT, 'group id'),
                                'name' => new external_value(PARAM_RAW, 'group name'),
                                'description' => new external_value(PARAM_RAW, 'group description'),
                            )
                        ), 'user groups', VALUE_OPTIONAL),
                    'roles' => new external_multiple_structure(
                        new external_single_structure(
                            array(
                                'roleid'       => new external_value(PARAM_INT, 'role id'),
                                'name'         => new external_value(PARAM_RAW, 'role name'),
                                'shortname'    => new external_value(PARAM_ALPHANUMEXT, 'role shortname'),
                                'sortorder'    => new external_value(PARAM_INT, 'role sortorder')
                            )
                        ), 'user roles', VALUE_OPTIONAL),
                    'preferences' => new external_multiple_structure(
                        new external_single_structure(
                            array(
                                'name'  => new external_value(PARAM_ALPHANUMEXT, 'The name of the preferences'),
                                'value' => new external_value(PARAM_RAW, 'The value of the custom field'),
                            )
                    ), 'User preferences', VALUE_OPTIONAL),
                    'enrolledcourses' => new external_multiple_structure(
                        new external_single_structure(
                            array(
                                'id'  => new external_value(PARAM_INT, 'Id of the course'),
                                'fullname' => new external_value(PARAM_RAW, 'Fullname of the course'),
                                'shortname' => new external_value(PARAM_RAW, 'Shortname of the course')
                            )
                    ), 'Courses where the user is enrolled - limited by which courses the user is able to see', VALUE_OPTIONAL)
                )
                )
            );
    }

    public static function get_events_parameters() {
        return new external_function_parameters(
            array(
                'start'    => new external_value(PARAM_INT, 'time start'),
                'end'      => new external_value(PARAM_INT, 'time end'),
            )
        );
    }

    public static function get_events($start, $end) {
        global $CFG, $USER, $DB;
        $params = self::validate_parameters(self::get_events_parameters(), array(
            'start' => $start,
            'end' => $end,
        ));

        $courses = array();
        foreach (enrol_get_users_courses($USER->id, true, $fields) as $c)
            $courses[] = $c->id;

        $events = calendar_get_events($params['start'], $params['end'], $USER->id, false, $courses);

        $return = array();
        foreach ($events as $e) {
            $return[] = array(
                'id' => $e->id,
                'name' => $e->name,
                'description' => $e->description,
                'format' => $e->format,
                'courseid' => $e->courseid,
                'groupid' => $e->groupid,
                'userid' => $e->userid,
                'repeatid' => $e->repeatid,
                'modulename' => $e->modulename,
                'eventtype' => $e->eventtype,
                'timestart' => $e->timestart,
                'timeduration' => $e->timeduration,
            );
        }

        return $return;
    }

    public static function get_events_returns() {
        return new external_multiple_structure(
            new external_single_structure(
                array(
                    'id'           => new external_value(PARAM_INT, 'ID of the event'),
                    'name'         => new external_value(PARAM_TEXT, 'name'),
                    'description'  => new external_value(PARAM_RAW, 'description'),
                    'format'       => new external_value(PARAM_INT, 'format'),
                    'courseid'     => new external_value(PARAM_INT, 'course id'),
                    'groupid'      => new external_value(PARAM_INT, 'group id'),
                    'userid'       => new external_value(PARAM_INT, 'user id'),
                    'repeatid'     => new external_value(PARAM_INT, 'repeat it'),
                    'modulename'   => new external_value(PARAM_TEXT, 'module name'),
                    'eventtype'    => new external_value(PARAM_TEXT, 'event type'),
                    'timestart'    => new external_value(PARAM_INT, 'timestart'),
                    'timeduration' => new external_value(PARAM_INT, 'timeduration'),
                )
            )
            );
    }

}
